package ComExWeb.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.inject.Named;

/**
 * Classe contendo métodos para encriptação utilizando o algorítimo de hash SHA-1.
 * @author Frederico
 */
@Named("criptografiaSHA")
public class CriptografiaSHA {

    private static final String hexDigits = "0123456789ABCDEF";

    public static String criptografar(String texto) throws RuntimeException {
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(texto.getBytes());
            BigInteger hash = new BigInteger(1, sha1.digest());
            String retornaSenha = hash.toString(16);
            return byteArrayToHexString(sha1.digest(texto.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            int j = ((int) b[i]) & 0xFF;
            buf.append(hexDigits.charAt(j / 16));
            buf.append(hexDigits.charAt(j % 16));
        }

        return buf.toString();
    }
}
